import { message, get, post } from '@/utils'
export interface Classify {
  children: Classify[]
  hasChildren: boolean
  icon: string
  id: any
  level: number
  parentId: string
  parentName: string
  path: string
  sort: number
  name: string
}
/**
 * 商品分类
 */
export default () => {
  const list = ref<Classify[]>([])
  const options = ref<Classify[]>([])
  const flag = ref(false)
  const reset = ref(false)
  const getList = (query: { level: number; parentId: any }, cb?): Promise<any[]> => {
    return new Promise((resolve, reject) => {
      get({ url: '/server-shop/sys-seller/goods/category/lazy-list', data: query }, ({ data }) => {
        reset.value = false
        data.map(v => {
          v.key = v.id
          v.isLeaf = !v.hasChildren
        })
        options.value = data

        if (query.level == 1) list.value = data
        else resolve(data)
        flag.value = true
        cb?.()
      })
    })
  }
  /**删除分类 */
  const remove = (id, cb?) => {
    post({ url: '/server-shop/sys-seller/goods/category/remove?ids=' + id }, ({ code, msg }) => {
      cb?.(code == 200)
      message({
        type: code == 200 ? 'success' : 'error',
        content: msg,
      })
    })
  }

  /**新增分类 */
  const add = (data, cb?) => {
    post({ url: '/server-shop/sys-seller/goods/category/submit', data }, ({ code, msg }) => {
      cb?.(code == 200)
      message({
        type: code == 200 ? 'success' : 'error',
        content: msg,
      })
    })
  }
  /**修改分类 */
  const update = (data, cb?) => {
    add(data, cb)
  }
  const tree = ref([])
  const getTree = () => {
    get({ url: '/server-shop/sys-seller/goods/category/tree' }, ({ data }) => {
      data.map(v => {
        v.key = v.id
        v.isLeaf = !v.hasChildren
      })
      tree.value = data
    })
  }
  return {
    list,
    getList,
    remove,
    update,
    add,
    reset,
    options,
    flag,
    tree,
    getTree,
  }
}
